package cl.utalca.robot.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cl.utalca.robot.domain.LanguageDTO;
import cl.utalca.robot.service.LanguageService;


@Controller
public class LanguageController {
	
	Logger logger = LoggerFactory.getLogger(LanguageController.class);
	
	@Autowired
	LanguageService languageService;
	
	@RequestMapping(value="/management", method=RequestMethod.GET)
	public String languageManagement(Model model){
	
        model.addAttribute("languageList", languageService.getLanguages());
        
        return "management";
	}
	
	@RequestMapping(value="/addLanguage", method=RequestMethod.GET)
	public String addLanguage(Model model){
		
		model.addAttribute(new LanguageDTO());
		model.addAttribute("action", "add");
		return "languageForm";
	}
	
	@RequestMapping(value="/editLanguage", method=RequestMethod.GET)
	public String editLanguage(@RequestParam("id")int languageId, Model model){
		
		LanguageDTO languageDTO = languageService.getLanguage(languageId);
		model.addAttribute(languageDTO);
		model.addAttribute("action", "edit");
		return "languageForm";
	}
	
	@RequestMapping(value="/deleteLanguage", method=RequestMethod.GET)
	public String deleteLanguage(@RequestParam("id")int languageId, Model model){
		
		Boolean success = languageService.deleteLanguage(languageId);
        if(success){
        	model.addAttribute("languageList", languageService.getLanguages());
        	return "management";
        }
        else{
        	return "error";
        }		
	}
	
	@RequestMapping(value="/saveLanguage", method=RequestMethod.POST)
	public String saveLanguage(LanguageDTO languageDTO, BindingResult bindingResult, Model model){
		
		Boolean success = false;
		
		if(languageDTO.getId() > 0 )
			success = languageService.updateLanguage(languageDTO);
		
		else{
			
			success = languageService.saveLanguage(languageDTO);
		}
		return languageManagement(model);
	}
}
